
import SDKAd from "./SDKAd";
import { SDKState, ResultCallback } from "../SDKDefine";

/**
 * 激励视频
 */
export default class SDKRewardedAd extends SDKAd {


    protected _callback: (r: SDKState) => void;

    preLoad() {
        if (this.has()) {
            this.setDirectShow(false)
            this.load()
        }
    }



    open(param: { callback: ResultCallback }) {
        if (!this.has()) {
            param.callback(SDKState.SUCCESS)
            return;
        }
        //如果预加载成功
        if (this._state == SDKState.SUCCESS) {
            this.show();
        } else {
            this.setDirectShow(true);
            this.load()
        }

    }

    load() {
        if (this.sdk) {
            this._state = SDKState.LOADING;
            if (!this.instance) {
                //posId vivo使用 adUnitId 其他平台使用
                this.instance = this.sdk.createRewardedVideoAd({ posId: this._adUnitId, adUnitId: this._adUnitId })
                this.instance.onLoad(this.bind(this.onLoad))
                this.instance.onError(this.bind(this.onError))
                this.instance.onClose(this.bind(this.onClose))
            } else {
                this.instance.load();
            }
        }

    }



    private onLoad() {
        this._state = SDKState.SUCCESS;
        if (this._isDirectShow) {
            this.show()
            this._isDirectShow = false;
        }
    }

    onError(err: any) {
        if (this._callback) {
            this._callback(0);
        }
    }

    onClose(res: any) {
        if (res && res.isEnded || res === undefined) {
            console.log('视频结束关闭 ')
            // 正常播放结束，可以下发游戏奖励
            if (this._callback) {
                this._callback(SDKState.SUCCESS)
            }
        } else {
            // 播放中途退出，不下发游戏奖励
            console.log('视频中途关闭 ')
            if (this._callback) {
                this._callback(SDKState.FAIL);
            }
        }

    }



    private show() {
        if (this.instance)
            this.instance.show();
    }

    private destroy() {
        if (this.instance) {
            this.instance.offLoad(this.unbind(this.onLoad))
            this.instance.offError(this.unbind(this.onError))
            this.instance.offClose(this.unbind(this.onClose))
            this.instance.destroy();
            this._callback = null;
            this.instance = null;
        }
    }


}
